#include "tcpServer.hpp"
#include <memory>
using namespace Server;

static void my_perrno(char *message)
{
    printf("%s使用有误,请加上端口\n", message);
}

void *ioservice(void *sockfd)
{
    // while (1)
    // {
    //     char buffer[1024];
    //     ssize_t n = read(sockfd, buffer, sizeof(buffer) - 1);
    //     if (n > 0)
    //     {
    //         buffer[n] = 0;
    //         cout << "Client say" << buffer << endl;
    //         string resp = buffer;
    //         resp += "[server echo]";
    //         write(sockfd, resp.c_str(), sizeof(resp));
    //     }
    // }

    //版本2：
    int *sock = static_cast<int *>(sockfd);
    while (1)
    {
        char buffer[1024];
        ssize_t n = read(*sock, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            cout << "Client say:" << buffer << endl;
            string res = buffer;
            res += "server echo:";
            write(*sock, res.c_str(), sizeof(res));
        }
    }
}
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        my_perrno(argv[0]);
        exit(1);
    }
    uint16_t port = atoi(argv[1]);

    unique_ptr<tcpServer> ret(new tcpServer(ioservice, port));
    ret->initServer();
    ret->start();

    return 0;
}
